0

I am sending Ajax request to php page using Javascript.

My main goals is to send ajax request to PHP page and get the response which I have done that already.

The problem is when the Ajax send back the response the Javascript cannot send this to HTML properly.

Look at my code so you can understand clearly.

Javascript code:

function get_rental_fee(){
        var count_model = $('#count_model').val();
        for(var i =0; i < count_model; i++){

        var hours = $('#hours').val();
        var modelid = $('#modelid_multi'+i).val();
        var get_tax = $('#get_tax_multi'+i).val();
        var get_counter = $('#get_counter_multi'+i).val();
        var myData = "hours="+hours+"&modelid="+modelid+"&get_tax="+get_tax;

    jQuery.ajax({

            type: "POST", // Post / Get method

            url: "get_rental_fee.php", //Where form data is sent on submission

            dataType:"text", // Data type, HTML, json etc.

            data:myData, //Form variables

            success:function(response){


                var result = response.split('|');

                       document.getElementById('rental_price_multi'+i).value=result[0];
                    document.getElementById('tax_multi'+i).value=result[1];


        },




            error:function (xhr, ajaxOptions, thrownError){

                //On error, we alert user

                alert(thrownError);

            }

            });

        }

    }

The problem is here:

document.getElementById('rental_price_multi'+i).value=result[0];
                        document.getElementById('tax_multi'+i).value=result[1];

The loop runs 3 times and Php is sending me back the response 3 times. But in Javascript Theses 2 lines are only showing VALUES of 3rd Times not 1st and 2nd. But I am receiving response of all 3 times.

Also when I run the code the javascript returns back an error:

Uncaught Type Error: Cannot set Property 'value' of null

Please help me where I am doing wrong

3
  • very common problem - will close as soon as I find an appropriate duplicate question Commented Mar 31, 2015 at 10:13
  • Can you please help me? Commented Mar 31, 2015 at 10:16
  • Hey Sachin, I am new to Javascript and Ajax can you please tell me where I am overwriting? And how can I send each every response to HTML? I want to show numeric values in the html. And I have multiple input types of same names but with different ID in HTML so that's why I need a Loop Commented Mar 31, 2015 at 10:20

2 Answers 2

2

Problem is $.ajax is by default async: true, so the value of i in loop is not the desired value when it reaches success. You can simply make the ajax sync:

$.ajax({
  async: false,
  ...
})

Edited:

If you still want to it to be async, you need to use closures.

for(var i =0; i < count_model; i++){
   (function(i){// closure `i`
     $.ajax({
       type: "POST",
       ...
     });
   })(i);//<-- for loop `i`
}
Sign up to request clarification or add additional context in comments.

4 Comments

Arvind, You are Gem.. Fantastic., Thanks for helping. This is really awesome.
Yes I am doing that but it is saying that I will have to wait for 3 minutes to accept it, lol
no, using async: false is ABSOLUTELY NOT the correct answer. I had real work to do, so couldn't answer just now.
Love you !!! xD , didn't know about closure for loop , thanks for sharing !!!
0

Your problem is that i inside the callback no longer has the value it did when you registered the callback. This is a very common problem.

A common solution is to "close over" the variable i so that it retains the correct value:

success: (function(i) {
    return function(response) {
        var result = response.split('|');
        document.getElementById('rental_price_multi'+i).value=result[0];
        document.getElementById('tax_multi'+i).value=result[1];
    })(i)

The outer function is passed i as a parameter, at which point its value in the inner callback function becomes fixed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.