javascript - Execute php url from jscript

316

So atm I have this which does work. Basicaly I want to execute the sendTo php file without changing to the new page. The location will cause my page to go to the php one and I don't want this. From the php page I can redirect it back to the original page, but I don't really like to do that. This is just some code added to an old app, it does not need to be pretty, it needs to work.

function showVal(newVal, taskid){
    var sendTo = "update_event.php?id_task=" + taskid + "&done=" + newVal;
    document.location.href = sendTo;
}
145

Answer

Solution:

You can use jQuery for this, what you need to do is perform an ajax request.

First include jQuery in your page:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

Then in your javascript you can do something like this:

function showVal(newVal, taskid) {
   $.get('update_event.php', { id_task: taskid, done: newVal}, 
       function(returnedData){
            console.log(returnedData);
   });
}
59

Answer

Solution:

ok, since you need a quick fix, i assume importing jquery wont be a whole deal this would be an example using ajax...

   function showVal(newVal, taskid){
    $.ajax({url: "update_event.php?id_task=" + taskid + "&done=" + newVal;, success: function(result){
        //here you can do things with the return result, for example, if you want to display it inside a div
            $("#div1").html(result);
        //or if you just want to alert it 
            alert(result);

        // if you dont want to do anithing, just leave the result in blank.

    }});

if you dont want to download jquery, you can just link it with this link

   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

hope it helps.

37

Answer

Solution:

Quick and dirty from the dark ages of web development, just hide a blank iFrame somewhere in the page, and go like this:

function showVal(newVal, taskid){
    var sendTo = "update_event.php?id_task=" + taskid + "&done=" + newVal;
    document.getElementById('yourhiddenframe').src = sendTo;
}

If you need to check for execution, look into onLoad for the iFrame.

People are also looking for solutions to the problem: php - Must I move data dependency out of my Controllers (and into Factories)?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.